package com.lcf.order.service.impl;


import com.lcf.order.client.ProductClient;
import com.lcf.order.constant.OrderStatusEnum;
import com.lcf.order.constant.PayStatusEnum;
import com.lcf.order.constant.ResultEnum;
import com.lcf.order.dto.CartDTO;
import com.lcf.order.dto.OrderDTO;
import com.lcf.order.entity.OrderDetail;
import com.lcf.order.entity.OrderMaster;
import com.lcf.order.entity.ProductInfo;
import com.lcf.order.exception.OrderException;
import com.lcf.order.mapper.OrderDetailMapper;
import com.lcf.order.mapper.OrderMasterMapper;
import com.lcf.order.service.OrderService;
import com.lcf.order.utils.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMasterMapper orderMasterMapper;

    @Autowired
    private ProductClient productClient;


    /**
     * private String buyerName;
     * private String buyerPhone;
     * private String buyerAddress;
     * private String buyerOpenid;
     * private BigDecimal orderAmount;
     * private Integer orderStatus;
     * private Integer payStatus;
     */

    /**
     * private String detailId;
     * private String orderId;
     * private String productId;
     * private String productName;
     * private BigDecimal productPrice;
     * private Integer productQuantity;
     * private String productIcon;
     */

    @Override
    @Transactional
    public int insertOrder() {
        OrderMaster orderMaster = new OrderMaster();
        String key = KeyUtil.genUniqueKey();
        orderMaster.setOrderId(key);
        orderMaster.setBuyerName("王小二");
        orderMaster.setBuyerPhone("13838384383");
        orderMaster.setBuyerAddress("深圳宝安");
        orderMaster.setBuyerOpenid("aaa-bbb-ccc");
        orderMaster.setOrderAmount(new BigDecimal(1999.9));
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        int i = orderMasterMapper.insertOrderMaster(orderMaster);

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setDetailId(UUID.randomUUID().toString().replace("-", ""));
        orderDetail.setOrderId(key);
        orderDetail.setProductId(UUID.randomUUID().toString().replace("-", ""));
        orderDetail.setProductName("酸辣大白菜");
        orderDetail.setProductPrice(new BigDecimal(1999.99));
        orderDetail.setProductQuantity(2);
        orderDetail.setProductIcon("http://aa.com");
        int j = orderDetailMapper.insertOrderDetail(orderDetail);
        return i + j;
    }

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();

        //查询商品信息(调用商品服务)
        List<String> productIdList = orderDTO.getOrderDetailList().stream()
                .map(OrderDetail::getProductId)
                .collect(Collectors.toList());
        List<ProductInfo> productInfoList = productClient.productListForOrder(productIdList);

        //计算总价
        BigDecimal orderAmout = new BigDecimal(BigInteger.ZERO);//设置初始值为0
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
            for (ProductInfo productInfo : productInfoList) {
                if (productInfo.getProductId().equals(orderDetail.getProductId())) {
                    //单价*数量
                    orderAmout = productInfo.getProductPrice()
                            .multiply(new BigDecimal(orderDetail.getProductQuantity()))//单价*数量
                            .add(orderAmout);//累加
                    BeanUtils.copyProperties(productInfo, orderDetail);
//                    orderDetail.setProductQuantity(productInfo.);
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
                    //订单详情入库
                    int j = orderDetailMapper.insertOrderDetail(orderDetail);
                }
            }
        }

        //扣库存(调用商品服务)
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productClient.productDecreaseStock(cartDTOList);

        //订单入库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmout);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterMapper.insertOrderMaster(orderMaster);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(String orderId) {
        //1.先查询订单
        OrderMaster orderMaster = orderMasterMapper.findOrderMasterById(orderId);
        if (null == orderMaster) {
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        //2.判断订单状态
        if (!OrderStatusEnum.NEW.getCode().equals(orderMaster.getOrderStatus())) {
            throw new OrderException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //3.修改订单状态为完结
        orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        orderMasterMapper.updateOrderMaster(orderMaster);

        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.findOrderDetailByOrderId(orderId);
        if (null == orderDetailList || orderDetailList.size() <= 0) {
            throw new OrderException(ResultEnum.ORDER_DETAIL_NOT_EXIST);
        }
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster, orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }


}
